package com.bioscript.standalone.IO;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import com.bioscript.standalone.IO.ContigsParsingEvents.ContigParsingEventTypes;
import com.bioscript.standalone.IO.baseClasses.BaseListener;
import com.bioscript.standalone.IO.baseClasses.BaseEvent.BaseEventTypes;

public class ContigsFileParser<E> extends BaseListener<ContigsParsingEvents> 
{
	private E value = null;
	private BufferedReader bufferedReader = null;
	boolean flag = false;
	
	public E getValue()
	{
		return value;
	}
	
	public void setValue(E obj)
	{
		this.value = obj;
	}
	
	private List<BaseListener<ContigsParsingEvents>> eventListeners = 
		new LinkedList<BaseListener<ContigsParsingEvents>>();
	
	public void addListener(BaseListener<ContigsParsingEvents> contigsParsingListener)
	{
		eventListeners.add(contigsParsingListener);
	}
	
	private void fireEvent(ContigsParsingEvents parseEvent)
	{
		for (BaseListener<ContigsParsingEvents> listener : eventListeners)
		{
			listener.handleEvent(parseEvent);
		}
	}
	
	public void parse(FileReader fileReader) throws IOException
	{
		addListener(this);
		bufferedReader = new BufferedReader(fileReader);
		fireEvent(new ContigsParsingEvents(null,BaseEventTypes.docStarted));
		String readLine = bufferedReader.readLine();
		while(readLine != null && !flag)
		{
			if (readLine.startsWith(">")) fireEvent(new ContigsParsingEvents(readLine,
					ContigParsingEventTypes.contigStarted));
			else fireEvent(new ContigsParsingEvents(readLine,ContigParsingEventTypes.seqread));
			if (flag)
			{
				flag = false;
				break;
			}
			readLine = bufferedReader.readLine();
		}
		fireEvent(new ContigsParsingEvents(null,BaseEventTypes.docEnded));
	}
	
	public void close()
	{
		flag = true;
	}
	
	public void removeAllListeners()
	{
		eventListeners.clear();
	}

	@Override
	public void handleEvent(ContigsParsingEvents event) {
		System.err.println("One should override the method handleEvent");
		System.exit(-1);
	}
}
